package cn.com.connext.scrm.utils;

import cn.com.connext.scrm.config.Constants;
//import cn.com.connext.scrm.domain.master.ErpLogistics;
import cn.com.connext.scrm.domain.master.ErpLogistics;
import cn.com.connext.scrm.domain.master.Member;
import cn.com.connext.scrm.domain.master.PrizeGood;
import cn.com.connext.scrm.service.dto.JsonResult;
import cn.com.connext.scrm.utils.wdtutils.WdtClient;
import cn.com.connext.scrm.web.rest.vm.TradeVM;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.connext.common.util.DateUtil;
import org.springframework.beans.BeanUtils;

import java.io.IOException;
import java.util.*;

public class ErpUtils {
    //需要填写买家地址用户信息，因此初步判断在买家填写完地址信息调用
        public static String sendOrder(String orderNo, PrizeGood good, Member member){
            String response ="";
            WdtClient client = new WdtClient(Constants.wdtsid, Constants.wdtAppkey, Constants.wdtAppsecret, Constants.wdtTradePushBaseUrl);
            List<Map<String, Object>> trade_list = new ArrayList<Map<String, Object>>();
            List<Map<String, Object>> order_list = new ArrayList<Map<String, Object>>();
            Map<String, Object> order_1 = new HashMap<String, Object>();
            order_1.put("oid", orderNo);//订单编号
            order_1.put("num", 1);
            order_1.put("price", 0);
            order_1.put("status", 30);//trade_status=30	已付款待发货(包含货到付款)，30只可以直接变更为70/ 80这2种状态
            order_1.put("refund_status", 0);//退款状态,无退款
            order_1.put("goods_id", good.getId());
            order_1.put("spec_id", "specid00111");
            order_1.put("goods_no", "goodsno00111");//货品编码 平台货品SPU编码，对应ERP货品编号，尽量不为空
            order_1.put("goods_name", good.getGoodName());
            order_1.put("spec_no", "specno_00111");//平台货品SKU唯一码，对应ERP商家编码，goods_no和spec_no不能同时为空
            order_1.put("discount", 0);		//子订单折扣
            order_1.put("adjust_amount", 0);	//手工调整,特别注意:正的表示加价,负的表示减价
            order_1.put("share_discount", 0);//分摊优惠


            order_list.add(order_1);
            String time = DateUtil.format(new Date(), "YYYYMMDDHHmmss");
            String orderChild = orderNo + time;
            Map<String, Object> trade_1 = new HashMap<String, Object>();
            trade_1.put("tid", orderChild);//订单id?
            trade_1.put("trade_status", 30);//已付款待发货(包含货到付款)，30只可以直接变更为70/ 80这2种状态
            trade_1.put("pay_status", "2");//,2:已付款
            trade_1.put("delivery_term", 1);//1:款到发货
            String tradeTime = DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss");
            trade_1.put("trade_time", tradeTime);//下单时间
            trade_1.put("buyer_nick", member.getNickName());
            trade_1.put("receiver_name", member.getNickName());//收件人
            trade_1.put("receiver_mobile", member.getMobile());//收件人电话
            trade_1.put("receiver_province", member.getProvince());
            trade_1.put("receiver_city", member.getCity());
            trade_1.put("receiver_district", member.getDistrictId());
            trade_1.put("receiver_address", member.getAddress());
//        trade_1.put("logistics_type", 4);
            trade_1.put("post_amount", 0);//邮费
            trade_1.put("cod_amount", 0);//货到付款金额
            trade_1.put("ext_cod_fee", 0);//货到付款买家费用
            trade_1.put("other_amount", 0);//其它收费
            trade_1.put("paid", 12);//已付款金额 paid = price * num
            trade_1.put("order_list", order_list);

            trade_list.add(trade_1);

            String trade_list_json = JSON.toJSONString(trade_list);
            //System.out.println(purchase_info_json);

            Map<String, String> params = new HashMap<String, String>();
            params.put("shop_no", Constants.wdtAppkey);
            params.put("trade_list", trade_list_json);
            try {
                 response = client.execute("trade_push.php", params);
                System.out.println(response);
            } catch (IOException e) {
                e.printStackTrace();
            }
            return response;
        }

        /**
         *  物流信息查询与同步
         * @param
         */
        public static JsonResult LogisticsSyncQuery() {
            JsonResult result =new JsonResult();
            WdtClient client = new WdtClient(Constants.wdtsid, Constants.wdtAppkey, Constants.wdtAppsecret, Constants.wdtLogisticsSyncQueryBaseUrl);
            Map<String, String> params = new HashMap<String, String>();
            params.put("shop_no", Constants.wdtAppkey);
            params.put("is_part_sync_able", "0");
            params.put("limit", "100");
            try {
                String response = client.execute("logistics_sync_query.php", params);
                System.out.println(response);
                JSONObject jsonObject = JSON.parseObject(response);
                String message = jsonObject.getString("trades");
                //2、使用JSONArray
                List<TradeVM> list = JSONObject.parseArray(message, TradeVM.class);
                if(list !=null && list.size() >0){
                    //物流同步回写
                    result = LogisticsSyncAck(list);
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return result;
        }




        /**
         * 物流信息同步
         * @param list
         */
        public static JsonResult LogisticsSyncAck(List<TradeVM> list ){
            JsonResult result =new JsonResult();
            WdtClient client = new WdtClient(Constants.wdtsid, Constants.wdtAppkey, Constants.wdtAppsecret, Constants.wdtLogisticsSyncAckBaseUrl);
            List<Map<String, Object>> logistics_list = new ArrayList<Map<String, Object>>();
            Map<String, Object> logistics_1 =null;
            ErpLogistics  erplogistics =null;
            List<ErpLogistics> erpLogisticsList = new ArrayList<>();
            if(list !=null && list.size() >0){
                for (TradeVM vm:list) {
                    logistics_1 = new HashMap<String, Object>();
                    logistics_1.put("rec_id", vm.getRec_id());
                    logistics_1.put("status", 0);
                    logistics_1.put("message", "同步成功");
                    logistics_list.add(logistics_1);
                    erplogistics =new ErpLogistics();
                    BeanUtils.copyProperties(vm, erplogistics);
                    erpLogisticsList.add(erplogistics);
                }
            }

            String logistics_list_json = JSON.toJSONString(logistics_list);
            Map<String, String> params = new HashMap<String, String>();
            params.put("logistics_list", logistics_list_json);
            try {
                String response = client.execute("logistics_sync_ack.php", params);
                JSONObject jsonObject = JSON.parseObject(response);
                System.out.println(response);
                result.setMessage(jsonObject.getString("message"));
                result.setState(jsonObject.getInteger("code"));
                result.setData(erpLogisticsList);
                return result;
            } catch (IOException e) {
                e.printStackTrace();
                result.setMessage(e.getMessage());
                result.setState(500);
                return result;
            }
        }

}
